import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:latlong2/latlong.dart';
import 'package:spring_fairy/model/mood_track_point.dart';
import 'package:spring_fairy/model/store.dart';
import 'package:spring_fairy/widget/mood_widget.dart';

import '../model/mood_type.dart';
import 'image_viewer.dart';

class PointData {
  final String name;
  final LatLng location;
  final DateTime? time;
  final int? mood;
  final String? content;
  final List<String>? imagePaths; // 可是 assets/... 或 http 开头的网络图

  PointData({
    required this.name,
    required this.location,
    this.time,
    this.mood,
    this.content,
    this.imagePaths,
  });

  factory PointData.fromMoodPoint(MoodTrackPoint point) {
    return PointData(
      name: point.locationName!,
      location: LatLng(point.latitude!, point.longitude!),
      // mood: point.moodType?.icon,
        mood: point.moodTypeId,
      content: point.description,
      imagePaths: point.images?.map((e) => e.imageUrl!).toList()
    );
  }
}

class MarkedPointCard extends StatefulWidget {
  final PointData point;
  final VoidCallback? onEdit;
  final VoidCallback? onDelete;

  MarkedPointCard({
    super.key,
    required this.point,
    this.onEdit,
    this.onDelete,
  });

  @override
  State<MarkedPointCard> createState() => _MarkedPointCardState();
}

class _MarkedPointCardState extends State<MarkedPointCard> {
  late PointData point;
  bool _isChange = false;
  MoodWidget? selectedMood;
  late List<MoodType> _moodTypes;
  late TextEditingController _noteController;
  final List<File> _images = [];
  late List<String>? _imagePaths;
  final ImagePicker _picker = ImagePicker();


  @override
  void initState() {
    super.initState();
    point = widget.point;
    _moodTypes = Store.moodTypes();
    _noteController = TextEditingController();
    _noteController.text = point.content ?? '';
    _imagePaths = point.imagePaths;

    for(MoodWidget moodType in MoodWidget.list) {
      if(moodType.name == point.name) {
        selectedMood = moodType;
        break;
      }
    }
  }

  @override
  void dispose() {
    super.dispose();
    _noteController.dispose();
  }

  void _showImageViewer(BuildContext context) {
    if (point.imagePaths == null || point.imagePaths!.isEmpty) return;

    int initialPage = 0;
    PageController controller = PageController(initialPage: initialPage);
    ValueNotifier<int> currentIndex = ValueNotifier(initialPage);

    showDialog(
      context: context,
      builder: (_) {
        return Dialog(
          backgroundColor: Colors.black,
          insetPadding: EdgeInsets.zero,
          child: Stack(
            alignment: Alignment.center,
            children: [
              PageView.builder(
                controller: controller,
                itemCount: point.imagePaths!.length,
                onPageChanged: (index) => currentIndex.value = index,
                itemBuilder: (context, index) {
                  final path = point.imagePaths![index];
                  final isNetwork = path.startsWith('http');
                  return InteractiveViewer(
                    child: isNetwork
                        ? Image.network(path, fit: BoxFit.contain)
                        : Image.asset(path, fit: BoxFit.contain),
                  );
                },
              ),

              // 图片页码指示器（居中底部）
              Positioned(
                bottom: 20,
                child: ValueListenableBuilder<int>(
                  valueListenable: currentIndex,
                  builder: (context, index, _) {
                    return Container(
                      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                      decoration: BoxDecoration(
                        color: Colors.black54,
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Text(
                        '${index + 1} / ${point.imagePaths!.length}',
                        style: TextStyle(color: Colors.white, fontSize: 16),
                      ),
                    );
                  },
                ),
              ),

              // 关闭按钮
              Positioned(
                top: 30,
                right: 20,
                child: IconButton(
                  icon: Icon(Icons.close, color: Colors.white, size: 28),
                  onPressed: () => Navigator.of(context).pop(),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final df = DateFormat('yyyy-MM-dd HH:mm');
    final MoodType moodType = Store.moodTypes().firstWhere((e) => e.id == widget.point.mood);

    return GestureDetector(
      onTap: () => _showImageViewer(context),
      child: Card(
        margin: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        elevation: 4,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        child: Padding(
          padding: EdgeInsets.all(12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(point.name, style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
              SizedBox(height: 6),
              Text('📍 ${point.location.latitude.toStringAsFixed(5)}, ${point.location.longitude.toStringAsFixed(5)}',
                  style: TextStyle(color: Colors.grey[700])),
              if (point.time != null)
                Text('🕒 ${df.format(point.time!)}', style: TextStyle(color: Colors.grey[600])),
              if (!_isChange && point.mood != null )
                Padding(
                  padding: EdgeInsets.only(top: 6),
                  child: Row(
                    children: [
                      Text('😊 心情：'),
                      SizedBox(
                        width: 30,
                          height: 30,
                          child:
                          MoodWidget.list.firstWhere((e) => e.name == moodType.name!).lottie)
                    ],
                  )
                ),
              if(_isChange)
                DropdownButtonFormField<MoodWidget>(
                  decoration: const InputDecoration(labelText: '选择心情'),
                  value: selectedMood,
                  items: MoodWidget.list.map((mood) {
                    return DropdownMenuItem(
                        value: mood,
                        child: SizedBox(
                          width: 30,
                          height: 30,
                          child: mood.lottie,
                        ));
                  }).toList(),
                  onChanged: (value) => setState(() => selectedMood = value),
                ),
              if (!_isChange && point.content != null && point.content!.isNotEmpty)
                Padding(
                  padding: EdgeInsets.only(top: 6),
                  child: Text('✏️ 内容：${point.content!}'),
                ),
              if(_isChange)
                Padding(
                  padding: const EdgeInsets.only(top: 8,bottom: 8),
                  child: TextField(
                    controller: _noteController,
                    onChanged: (text) {
                      setState(() {
                        _noteController.text = text;
                      });
                    },
                    decoration: const InputDecoration(
                      labelText: '描述内容',
                      border: OutlineInputBorder(),
                    ),
                    maxLines: 3,
                  ),
                ),
              // 多图预览（缩略图，只展示第一张）
              if (!_isChange && point.imagePaths != null && point.imagePaths!.isNotEmpty)
                Padding(
                  padding: EdgeInsets.only(top: 10),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: point.imagePaths!.first.startsWith('http')
                        ? Image.network(
                      point.imagePaths!.first,
                      height: 160,
                      width: double.infinity,
                      fit: BoxFit.cover,
                    )
                        : Image.asset(
                      point.imagePaths!.first,
                      height: 160,
                      width: double.infinity,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                if(_isChange)
                  Wrap(
                    spacing: 8,
                    runSpacing: 8,
                    children: [
                      if(_imagePaths != null)
                      for (int i = 0; i < _imagePaths!.length; i++)
                        Stack(
                          children: [
                            GestureDetector(
                              onTap: () => __showImageViewer(i,false),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(10),
                                child: Image.network(
                                  _imagePaths![i],
                                  width: 80,
                                  height: 80,
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                            Positioned(
                              top: -8,
                              right: -8,
                              child: IconButton(
                                icon: const Icon(Icons.cancel, color: Colors.redAccent, size: 20),
                                onPressed: () => _removeImage(i),
                                padding: EdgeInsets.zero,
                                constraints: const BoxConstraints(),
                              ),
                            ),
                          ],
                        ),
                      for (int i = 0; i < _images.length; i++)
                        Stack(
                          children: [
                            GestureDetector(
                              onTap: () => __showImageViewer(i,true),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(10),
                                child: Image.file(
                                  _images[i],
                                  width: 80,
                                  height: 80,
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                            Positioned(
                              top: -8,
                              right: -8,
                              child: IconButton(
                                icon: const Icon(Icons.cancel, color: Colors.redAccent, size: 20),
                                onPressed: () => _removeImage(i),
                                padding: EdgeInsets.zero,
                                constraints: const BoxConstraints(),
                              ),
                            ),
                          ],
                        ),
                      // 添加按钮：拍照
                      GestureDetector(
                        onTap: () => _pickImage(ImageSource.camera),
                        child: Container(
                          width: 80,
                          height: 80,
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey),
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: const Icon(Icons.camera_alt, size: 28, color: Colors.grey),
                        ),
                      ),

                      // 添加按钮：相册
                      GestureDetector(
                        onTap: () => _pickImage(ImageSource.gallery),
                        child: Container(
                          width: 80,
                          height: 80,
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey),
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: const Icon(Icons.photo, size: 28, color: Colors.grey),
                        ),
                      ),
                    ],
                  ),
              if (widget.onEdit != null || widget.onDelete != null)
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    if(_isChange)
                      IconButton(onPressed: (){},
                          icon:Icon(Icons.update,color: Colors.green,),
                        tooltip: '更新'),
                    if (widget.onEdit != null)
                      IconButton(
                        icon: Icon(Icons.edit, color: Colors.blue),
                        onPressed: () {
                          setState(() {
                            _isChange = !_isChange;
                          });
                          widget.onEdit?.call();
                        },
                        tooltip: "编辑",
                      ),
                    if (widget.onDelete != null)
                      IconButton(
                        icon: Icon(Icons.delete, color: Colors.red),
                        onPressed: () {
                          widget.onDelete?.call();
                        },
                        tooltip: "删除",
                      ),
                  ],
                ),
            ],
          ),
        ),
      ),
    );
  }


  void __showImageViewer(int initialIndex,bool isFile) {
    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          backgroundColor: Colors.black87,
          insetPadding: const EdgeInsets.all(16),
          child: ImageViewer(images: isFile ? _images : _imagePaths!, initialIndex: initialIndex),
        );
      },
    );
  }


  Future<void> _pickImage(ImageSource source) async {
    final XFile? image = await _picker.pickImage(source: source);
    if (image != null) {
      setState(() {
        _images.add(File(image.path));
      });
    }
  }

  void _removeImage(int index) {
    setState(() {
      _images.removeAt(index);
    });
  }
}


